class AlbumsController < ApplicationController
  before_filter :login_required

  def new
    @album = Album.new
  end
  
  def create
    @album = Album.new params[:album]
    @album.user_id = session[:user]
    if request.post? and @album.save
      flash[:notice] = "\"#{@album.title}\" has been created."
      redirect_to :controller=>"gallery", :action=>"list"
    end
  end
  
  def edit
    @album = Album.find(params[:id])
  end
  
  def update
    @album = Album.find(params[:id])
    if request.post? and @album.update_attributes(params[:album]) and @album.save
      flash[:notice] = "\"#{@album.title}\" has been saved."
      redirect_to :controller=>"gallery", :action=>"album", :id => @album
    else
      render :action=>"edit"
    end
  end

  def add_photo
    @photo = Photo.find(params[:id].split("_")[1])
    @album = Album.find(params[:album_id])
    @album.photos << @photo if !@album.photos.include?(@photo)
    render :partial=>"/gallery/album" and return
  end
  
  # Removes all the photos from the album, but keeps the album
  def clear
    @album = Album.find(params[:id])
    @album.photos.clear
    flash[:notice] = "\"#{@album.title}\" has been cleared."
    redirect_to :controller=>"gallery", :action=>"album", :id => @album
  end
  
  # Removes one photo from an album
  def remove
    album = Album.find(params[:album_id])
    photo = Photo.find(params[:id].split("_")[1])
    album.photos.delete(photo)
    album.save
    render :partial=>"gallery/photo", :collection=>album.photos
  end
  
  # Removes all the photos from the album, but keeps the album
  def destroy
    @album = Album.find(params[:id])
    title = @album.title
    @album.destroy
    flash[:notice] = "\"#{title}\" has been destroyed."
    redirect_to :controller=>"gallery", :action=>"list"
  end

end
